import { TypingContext, TypingStateActionType } from '../../store'
import AnalysisButton from '../AnalysisButton'
import DictChapterButton from '../DictChapterButton'
import ErrorBookButton from '../ErrorBookButton'
import Setting from '../Setting'
import WordDictationSwitcher from '../WordDictationSwitcher'
import { ListPreviewButton } from '../WordList'
import { isOpenDarkModeAtom, randomConfigAtom } from '@/store'
import { recordAnalysisAction, recordErrorBookAction } from '@/utils'
import { useAtom, useAtomValue } from 'jotai'
import { useCallback, useContext, useState } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import { useNavigate } from 'react-router-dom'
import IconBook from '~icons/bxs/book'
import ChartPie from '~icons/heroicons/chart-pie-solid'
import IconCog6Tooth from '~icons/heroicons/cog-6-tooth-solid'
import IconMoon from '~icons/heroicons/moon-solid'
import IconSun from '~icons/heroicons/sun-solid'
import IconPause from '~icons/tabler/player-pause'
import IconPlay from '~icons/tabler/player-play'
import IconRefresh from '~icons/tabler/refresh'

export default function Switcher({ isLoading }: { isLoading?: boolean }) {
  const [isOpenDarkMode, setIsOpenDarkMode] = useAtom(isOpenDarkModeAtom)
  const { state, dispatch } = useContext(TypingContext) ?? {}
  const randomConfig = useAtomValue(randomConfigAtom)
  const navigate = useNavigate()

  const changeDarkModeState = () => {
    setIsOpenDarkMode((old) => !old)
  }

  const changeTransVisibleState = () => {
    if (dispatch) {
      dispatch({ type: TypingStateActionType.TOGGLE_TRANS_VISIBLE })
    }
  }

  const onToggleIsTyping = useCallback(() => {
    if (!isLoading && dispatch) dispatch({ type: TypingStateActionType.TOGGLE_IS_TYPING })
  }, [isLoading, dispatch])

  const onClickRestart = useCallback(() => {
    if (dispatch) dispatch({ type: TypingStateActionType.REPEAT_CHAPTER, shouldShuffle: randomConfig.isOpen })
  }, [dispatch, randomConfig.isOpen])

  // 错题本跳转
  const toErrorBook = useCallback(() => {
    navigate('/error-book')
    recordErrorBookAction('open')
  }, [navigate])

  // 数据统计跳转
  const toAnalysis = useCallback(() => {
    navigate('/analysis')
    recordAnalysisAction('open')
  }, [navigate])

  // 设置弹窗
  const [isSettingOpen, setIsSettingOpen] = useState(false)
  const openSetting = useCallback(() => setIsSettingOpen(true), [])
  const closeSetting = useCallback(() => setIsSettingOpen(false), [])

  useHotkeys(
    'ctrl+shift+v',
    () => {
      changeTransVisibleState()
    },
    { enableOnFormTags: true, preventDefault: true },
    [],
  )

  return (
    <div className="fixed right-0 top-1/2 z-40 flex -translate-y-1/2 flex-col items-center gap-3 rounded-l-2xl bg-white/80 px-2 py-4 shadow-lg dark:bg-gray-900/80">
      <DictChapterButton />
      <div className="flex w-full flex-col items-center">
        <button
          className="flex w-full items-center justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          type="button"
          onClick={onToggleIsTyping}
          aria-label={state?.isTyping ? '暂停' : '开始'}
        >
          {state?.isTyping ? <IconPause className="h-6 w-6" /> : <IconPlay className="h-6 w-6" />}
          <span className="text-base">{state?.isTyping ? '暂停' : '开始'}</span>
        </button>
        <button
          className="flex w-full items-center justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          type="button"
          onClick={onClickRestart}
          aria-label="重新开始"
        >
          <IconRefresh className="h-6 w-6" />
          <span className="text-base">重新开始</span>
        </button>
        <button
          className="flex w-full items-center justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          onClick={() => (document.querySelector("[title='单词预览']") as HTMLElement)?.click()}
        >
          <ListPreviewButton />
          <span className="text-base">单词预览</span>
        </button>
        <button
          className="flex w-full items-center justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          onClick={() => (document.querySelector("[aria-label='默写模式']") as HTMLElement)?.click()}
        >
          <WordDictationSwitcher />
          <span className="text-base">默写模式</span>
        </button>
        <button
          className="flex w-full items-center justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          type="button"
          onClick={toErrorBook}
        >
          <IconBook className="h-6 w-6" />
          <span className="text-base">错题本</span>
        </button>
        <button
          className="flex w-full items-center justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          type="button"
          onClick={toAnalysis}
        >
          <ChartPie className="h-6 w-6" />
          <span className="text-base">数据统计</span>
        </button>
        <button
          className="flex w-full items-center justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          type="button"
          onClick={(e) => {
            changeDarkModeState()
            e.currentTarget.blur()
          }}
          aria-label="深色模式"
        >
          {isOpenDarkMode ? <IconMoon className="icon" /> : <IconSun className="icon" />}
          <span className="text-base">深色模式</span>
        </button>
        {/* <button className="flex items-center w-full justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white">
          <StartButton isLoading={!!isLoading} />
          <span className="text-base">开始</span>
        </button> */}

        <button
          className="flex w-full items-center justify-start gap-2 rounded p-2 text-lg text-green-500 outline-none transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white"
          type="button"
          onClick={openSetting}
        >
          <IconCog6Tooth className="h-6 w-6" />
          <span className="text-base">设置</span>
        </button>
      </div>

      {/* <Tooltip className="h-7 w-7" content="指法图示">
        <HandPositionIllustration></HandPositionIllustration>
      </Tooltip> */}

      {/* 设置弹窗 */}
      {isSettingOpen && <Setting isOpen={isSettingOpen} onClose={closeSetting} />}
    </div>
  )
}
